package com.tangruojie.controller;

import com.tangruojie.domain.Book;
import com.tangruojie.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean flag = bookService.save(book);
        return new Result(
                flag,
                flag ? Code.SAVE_OK : Code.SAVE_ERR,
                flag ? "保存成功" : "保存失败"
        );
    }

    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean flag = bookService.update(book);
        return new Result(
                flag,
                flag ? Code.UPDATE_OK : Code.UPDATE_ERR,
                flag ? "修改成功" : "修改失败"
        );
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag = bookService.delete(id);
        return new Result(
                flag,
                flag ? Code.DELETE_OK : Code.DELETE_ERR,
                flag ? "删除成功" : "删除失败"
        );
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {

//        int i = 1 / 0;

        Book book = bookService.getById(id);
        return new Result(
                book,
                book != null ? Code.GET_OK : Code.GET_ERR,
                book != null ? "查询成功" : "查询失败"
        );
    }

    @GetMapping
    public Result getAll() {
        List<Book> list = bookService.getAll();
        return new Result(
                list,
                list != null ? Code.GET_OK : Code.GET_ERR,
                list != null ? "查询成功" : "查询失败"
        );
    }

}
